import cv2
import numpy as np

if __name__ == '__main__':
    video_path = ''

    capture = cv2.VideoCapture(video_path)
    # - history表示过往帧数，500帧，选择history = 1就变成两帧差
    # - dist2Threshold 像素与样本之间的平方距离上的阈值，以确定像素是否接近该样本。该参数不影响背景更新。
    # - detectShadows 是否保留阴影检测，选择False这样速度快点。
    pBgmodel = cv2.createBackgroundSubtractorKNN(200, detectShadows=False)

    # - history表示过往帧数，500帧，选择history = 1就变成两帧差
    # - varThreshold表示像素与模型之间的马氏距离，值越大，只有那些最新的像素会被归到前景，值越小前景对光照越敏感。
    # - detectShadows 是否保留阴影检测，选择False这样速度快点。
    # pBgmodel=cv2.createBackgroundSubtractorMOG2(200,60,False)

    # CNT 可能只在opencv-python-contrib包里面才有,opencv-python里面无
    # pBgmodel=cv2.createBackgroundSubtractorCNT()
    assert (capture.isOpened, 'open video error!')
    while True:
        ret, frame = capture.read()
        if frame is None:
            break
        fgMask = pBgmodel.apply(frame)
        # 闭运算去除部分噪点
        element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
        fgMask = cv2.morphologyEx(fgMask, cv2.MORPH_CLOSE, element)
        foreGround = np.zeros_like(fgMask).astype(np.uint8)
        foreGround = cv2.copyTo(frame, fgMask)

        cv2.imshow('Frame', frame)
        cv2.imshow('FG Mask', fgMask)
        cv2.imshow('foreGround', foreGround)

        keyboard = cv2.waitKey(1)
        if keyboard == 27:
            break
    capture.release()
    cv2.destroyAllWindows()
